<template>
  <v-app>
    <v-main>
      <v-container fluid class="pa-0 fill-height">
        <v-row no-gutters class="d-flex flex-row" style="height: 100%; flex-wrap: nowrap;">
          <!-- 左侧 Tab 栏 -->
          <SidebarTabs v-model="chooseTab" @update:tab="updateTab" />

          <!-- 中间 ChatList -->
          <v-col style="flex: none; width: 300px;">
            <v-card class="fill-height" flat>
              <ChatList
                :chatList="chatStore.chatList"
                :selectedChat="chatStore.selectedChat"
                @select="selectChat"
                :choose-tab="chooseTab"
              />
            </v-card>
          </v-col>

          <!-- 右侧聊天窗口 -->
          <v-col style="flex: 1 1 auto;">
            <ChatWindow
              v-if="chatStore.selectedChat"
              :id="chatStore.selectedChat.id"
              :type="chatStore.selectedChat.type"
              :title="chatStore.selectedChat.name"
              :name="chatStore.selectedChat.name"
              @send="sendMessage"
            />
          </v-col>
        </v-row>

        <!-- 登录注册遮罩 -->
        <v-overlay
          v-model="showLogin"
          persistent
          class="align-center justify-center"
          scrim="rgba(0, 0, 0, 0.6)"
        >
          <LoginRegisterDialog @login-success="onLoginSuccess" @close="showLogin = false" />
        </v-overlay>
      </v-container>
    </v-main>
  </v-app>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useChatStore, type ChatInfo } from '@/stores/sessions' // pinia store路径
import ChatWindow from './ChatWindow.vue'
import ChatList from './ChatList.vue'
import SidebarTabs from './SidebarTabs.vue'
import LoginRegisterDialog from './LoginRegisterDialog.vue'
import { useStompClient } from '@/composables/useStompClient'

const chooseTab = ref('friends')
const showLogin = ref(false)
const stomp = useStompClient()

const chatStore = useChatStore()

onMounted(async () => {
  const userId = localStorage.getItem('user_id')
  if (!userId) {
    showLogin.value = true // 打开登录组件
  } else {
    await chatStore.loadChatList() // 拉取好友和群组数据
  }
})

watch(chooseTab, (val) => {
  showLogin.value = val === 'login'
})

function updateTab(value: string) {
  chooseTab.value = value
}

function onLoginSuccess(token: string) {
  localStorage.setItem('jwt_token', token)
  showLogin.value = false
  chooseTab.value = 'friends'
  chatStore.loadChatList() // 登录成功后拉取数据
}

function selectChat(chat: ChatInfo) {
  chatStore.selectChat(chat)
}

function sendMessage(content: string) {
  chatStore.sendMessage(content)
}
</script>
